package com.profgj.profgj.controller;

import com.profgj.profgj.entity.User;
import com.profgj.profgj.entity.UserNotify;
import com.profgj.profgj.enums.ServerStatus;
import com.profgj.profgj.service.UserNotifyService;
import com.profgj.profgj.service.UserService;
import com.profgj.profgj.utils.EmptyUtils;
import com.profgj.profgj.utils.ReturnOperator;
import com.profgj.profgj.vo.EmptyObject;
import com.profgj.profgj.vo.ResultMsg;
import com.profgj.profgj.vo.ReturnResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户通知控制层
 */
@RestController
@RequestMapping("/notify")
@Api(tags = {"用户通知"}, description = "用户通知提醒")
public class UserNotifyController {

    /**
     * 返回空对象的替代品
     */
    private EmptyObject emptyObject = new EmptyObject();

    /**
     * 用户通知服务对象
     */
    @Resource
    private UserNotifyService userNotifyService;

    /**
     * 用户服务对象
     */
    @Resource
    private UserService userService;

    /**
     * # 检测用户没有上报开始的提示日期
     */
    @Value("${system.task.checkday}")
    private Integer checkDay = null;

    /**
     * 月初1号企业用都初始通知都初始为0, initday初始的日期
     */
    @Value("${system.task.initday}")
    private Integer initDay = null;
    
    
    /**
     * 查询企业用户的用户通知
     * @param userId    企业用户id
     * @return
     */
    @GetMapping("/usr/notify/{userId}")
    @ApiOperation(value = "查询企业用户的用户通知",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "userId", value = "用户id",required = true, dataType = "Integer", paramType = "Integer")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> queryEnUserNotifyMethod(@PathVariable("userId")Integer userId) {

        // 参数校验
        if (!EmptyUtils.isIntegerEmpty(userId)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        User user = userService.queryById(userId);
        // 不是管理员的情况下
        if (user.getRoleId() != 1) {
            UserNotify userNotify = userNotifyService.queryByEnUserId(user.getId());
            // 获取今天 多少号
            Integer currentDay = Integer.parseInt(new SimpleDateFormat("dd").format(new Date()));
            // 范围在 1-26之间
            if (initDay >= currentDay &&  currentDay >= checkDay) {
                // 用户未读通知的情况下
                if (userNotify.getRead() == 0) {
                    return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                            new ArrayList<>(), userNotify, HttpStatus.OK);
                }
            } else {
                // 不在1-26 之前的情况下
                // 对为上报的用户进行通知
                if (userNotify.getReport() == 0) {
                    return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                            new ArrayList<>(), userNotify, HttpStatus.OK);
                }
            }
        }

        /**
         * 是管理员的情况下 查询未读的所有 通知
         */
        List<UserNotify> userNotifys = userNotifyService.queryByAdminUserId(user.getId(), 0);
        if (!EmptyUtils.isUserNotifyListEmpty(userNotifys)) {
            return ReturnOperator.createResultMsg("", ServerStatus.QUERY_MESSAGE_ERR, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                userNotifys, emptyObject, HttpStatus.OK);
    }


    /**
     * 分页获取管理员通知提醒
     * @param draw
     * @param start
     * @param length
     * @param session
     * @return
     */
    @GetMapping("/user/notify")
    @ApiOperation(value = "分页查询企业",consumes = "application/json", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "draw", value = "绘制次数",required = true, dataType = "Integer", paramType = "Integer"),
            @ApiImplicitParam(name = "start", value = "查询起始位置",required = true, dataType = "Integer", paramType = "Integer"),
            @ApiImplicitParam(name = "length", value = "查询条数",required = true, dataType = "Integer", paramType = "Integer")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ReturnResult> queryListUserNotifyMethod(Integer draw,
                                                               Integer start,
                                                               Integer length,
                                                               @ApiIgnore HttpSession session){

        // 分页参数校验
        if(!EmptyUtils.isIntegerEmpty(start) && !EmptyUtils.isIntegerEmpty(length)){
            return ReturnOperator.createResultMsg(draw,0, 0,
                    new ArrayList<>(), HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));

        // 用户id和未读标志分页查询通知提醒
        List<UserNotify> userNotifyList = userNotifyService.queryAllByLimitAndUserId(user_id,start,length);

        int total = userNotifyService.queryByUserId(user_id).size();

        // 查询校验
        if(!EmptyUtils.isUserNotifyListEmpty(userNotifyList)) {
            return ReturnOperator.createResultMsg(draw,0, 0,
                    new ArrayList<>(), HttpStatus.OK);
        }

        Map<String,Object> data = new HashMap<>();
        data.put("draw",1);
        data.put("recordsTotal",total);
        data.put("recordsFiltered",total);
        data.put("data",userNotifyList);

        // 返回数据
        ResponseEntity<ReturnResult> resultMsg = ReturnOperator.createResultMsg(draw, total,
                total, userNotifyList, HttpStatus.OK);
        return resultMsg;

    }


    /**
     * 更变用户通知消息 为已读
     */
    @PutMapping("/usr/notify/{notifyId}")
    @ApiOperation(value = "更变用户通知消息为已读",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "notifyId", value = "通知消息id",required = true, dataType = "Long", paramType = "Long")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> changeUserNotifyLiftReadMethod(@PathVariable("notifyId") Long notifyId,@ApiIgnore HttpSession session) {
        // id查询通知
        UserNotify userNotify = userNotifyService.queryById(notifyId);
        // 查询校验
        if (!EmptyUtils.isUserNotifyEmpty(userNotify)){
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 设置通知已读
        userNotify.setRead(1);
        // 更新通知
        UserNotify userNotify_update = userNotifyService.update(userNotify);
        // 更新判空
        if (!EmptyUtils.isUserNotifyEmpty(userNotify)){
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_UPDATE_ERR, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }
        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_UPDATE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), userNotify_update, HttpStatus.OK);
    }


    /**
     * 通知ID删除通知
     * @param id
     * @return
     */
    @DeleteMapping("/usr/notify/{id}")
    @ApiOperation(value = "通知ID删除通知",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "id", value = "通知消息id",required = true, dataType = "Long", paramType = "Long")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> deleteUserNotifyByIdMethod(@PathVariable("id")Long id){

        // 参数校验
        if(!EmptyUtils.isLongEmpty(id)){
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // id删除操作
        if (!userNotifyService.deleteById(id)){
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_DELETE_ERR, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), emptyObject, HttpStatus.OK);
    }

    /**
     * 循环删除
     * @param ids
     * @return
     */
    @GetMapping("/usr/notify/list/del")
    @ApiOperation(value = "通知ID删除通知",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "ids", value = "通知消息id数组",required = true, dataType = "Long", paramType = "Long")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> batchDeleteUserNotify(Long[] ids){

        // 参数校验
        if(!EmptyUtils.isIdsEmpty(ids)){
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 循环删除
        for(Long id: ids){
            userNotifyService.deleteById(id);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), emptyObject, HttpStatus.OK);
    }


    /**
     * 循环更变已读
     * @param ids
     * @return
     */
    @GetMapping("/usr/notify/list/read")
    @ApiOperation(value = "循环更变已读",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "ids", value = "通知消息id数组",required = true, dataType = "Long", paramType = "Long")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> batchChangeUserNotifyRead(Long[] ids){

        // 参数校验
        if(!EmptyUtils.isIdsEmpty(ids)){
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 循环更新已读
        for(Long id: ids){
            UserNotify userNotify = userNotifyService.queryById(id);
            userNotify.setRead(1);
            userNotifyService.update(userNotify);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_UPDATE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), emptyObject, HttpStatus.OK);
    }
}
